package com.battery.eason.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battery.eason.config.JwtTokenUtil;
import com.battery.eason.pojo.*;
import com.battery.eason.mapper.FroUserMapper;
import com.battery.eason.service.IFroUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.battery.eason.utils.DateTimeUtil;
import com.battery.eason.utils.MD5Util;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangSiYuan
 * @since 2021-08-16
 */
@Service
public class FroUserServiceImpl extends ServiceImpl<FroUserMapper, FroUser> implements IFroUserService {

    @Autowired
    private FroUserMapper froUserMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${upload.baseUrl}")
    private String baseUrl;

    @Override
    public RespPageBean pageList(Integer currentPage, Integer pageSize, String name, String phone, Integer status) {
        RespPageBean respPageBean = new RespPageBean();
        Page<FroUser> froUserPage = new Page<>(currentPage,pageSize);
        IPage<FroUser> froUserIPage = froUserMapper.getFroUserByPage(froUserPage,name,phone,status);
        respPageBean.setData(froUserIPage.getRecords());
        respPageBean.setTotal(froUserPage.getTotal());
        return respPageBean;
    }

    @Override
    public RespBean login(SysLoginParams loginParams, HttpServletRequest request) {
        //首先判断验证码是否正确
        if (!loginParams.getCaptcha().equals(request.getServletContext().getAttribute(loginParams.getUuid()))) {
            return RespBean.error("验证码错误!");
        }
        //通过用户名判断用户是否存在
        FroUser froUser = froUserMapper.selectOne(new QueryWrapper<FroUser>().eq("username", loginParams.getUsername()));
        String token = null;
        if (null == froUser) {
            //说明用户不存在
            FroUser registUser = new FroUser();
            registUser.setStatus(1);
            registUser.setPassword(MD5Util.md5(loginParams.getPassword()));
            registUser.setUsername(loginParams.getUsername());
            registUser.setCreateTime(DateTimeUtil.getSysTime());
            registUser.setAvatar("43572F888DB1466188479EABBD8E82FE.png");
            registUser.setBalance("0");
            registUser.setPhone(loginParams.getPhone());
            token = jwtTokenUtil.generateTokenFroUser(registUser);
            request.getServletContext().setAttribute(loginParams.getUsername(),registUser);
            froUserMapper.insert(registUser);
        } else {
            //说明用户存在， 判断密码是否正确
            if (!MD5Util.md5(loginParams.getPassword()).equals(froUser.getPassword())) {
                return RespBean.error("用户名或密码错误!");
            }
            token = jwtTokenUtil.generateTokenFroUser(froUser);
            request.getServletContext().setAttribute(loginParams.getUsername(),froUser);
        }
        //设置token返回前端
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //根据用户名查询出用户信息返回前端页面
        String userNameFromToken = jwtTokenUtil.getUserNameFromToken(token);
        FroUser froUser1 = froUserMapper.selectOne(new QueryWrapper<FroUser>().eq("username", userNameFromToken));
        map.put("user",froUser1);
        //用户登录成功将用户信息存储到session里面
        request.getServletContext().removeAttribute(loginParams.getUuid());
        return RespBean.success("用户登录成功!",map);
    }

    @Override
    public RespBean uploadAvatar(MultipartFile imgFile, Integer id) {
        String uuid = UUID.randomUUID().toString().toUpperCase(Locale.ROOT).replaceAll("-","");
        String realFileName = uuid + "." + imgFile.getOriginalFilename().split("\\.")[1];
        try {

//            File file = new File( "/data/share_battery/upload" + File.separator+realFileName);
            File file = new File( baseUrl + File.separator+realFileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            imgFile.transferTo(file);
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFileName(realFileName);
            fileInfo.setPath(file.getPath());
            fileInfo.setCreateTime(DateTimeUtil.getSysTime());
            //更新数据库中的文件信息
            FroUser froUser = froUserMapper.selectById(id);
            froUser.setAvatar(realFileName);
            int i = froUserMapper.updateById(froUser);
            if (i != 0) {
                return RespBean.success("用户头像修改成功");
            }
            return RespBean.error("用户头像修改失败!");
        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error("文件上传失败!");
        }
    }
}
